package masterjava.common.client.gxt.base.tree;

import com.extjs.gxt.ui.client.data.ModelKeyProvider;
import com.extjs.gxt.ui.client.data.TreeLoader;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.store.StoreSorter;
import com.extjs.gxt.ui.client.store.TreeStore;

/**
 * User: gkislin
 * Date: 8/1/11
 */
public class GenericTreeStore extends TreeStore<GenericTreeModel> {
    public GenericTreeStore(TreeLoader<GenericTreeModel> namedModelTreeLoader) {
        super(namedModelTreeLoader);
        setKeyProvider(new ModelKeyProvider<GenericTreeModel>() {
            public String getKey(GenericTreeModel model) {
                return model.<String>get(GenericTreeModel.TYPE) + "_" + model.<String>get(GenericTreeModel.ID);
            }
        });
        setStoreSorter(new StoreSorter<GenericTreeModel>() {
            @Override
            public int compare(Store<GenericTreeModel> store, GenericTreeModel m1, GenericTreeModel m2, String property) {
                boolean m1Folder = m1 instanceof FolderModel;
                boolean m2Folder = m2 instanceof FolderModel;

                if (m1Folder && !m2Folder) {
                    return -1;
                } else if (!m1Folder && m2Folder) {
                    return 1;
                }

                return m1.getKey().compareTo(m2.getKey());
            }
        });
    }
}